package com.ehualu.check.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author: 吴敬超
 * @Date: 2020/7/9 11:10
 */
public final class LoadProperties {
    private static final Logger LOG = LoggerFactory.getLogger(LoadProperties.class);


    private static Properties producerProps = new Properties();


    private static LoadProperties instance = null;

    private LoadProperties() {
//        String filePath = System.getProperty("user.dir") + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator;
        String filePath = System.getProperty("user.dir") + File.separator + "conf" + File.separator;


        LOG.info("Properties File Path is:" + filePath + "producer.properties");

        try {
            File proFile = new File(filePath + "producer.properties");

            if (proFile.exists()) {
                producerProps.load(new FileInputStream(filePath + "producer.properties"));
            }


        } catch (IOException e) {
            LOG.info("The Exception occured.", e);
        }
    }

    public synchronized static LoadProperties getInstance() {
        if (null == instance) {
            instance = new LoadProperties();
        }

        return instance;
    }

    /**
     * 获取配置文件参数值，如果没有获取到，则返回defValue默认值
     *
     * @param key      properites的key值
     * @param defValue 默认值
     * @return
     */
    public String getValues(String key, String defValue) {
        String rtValue = null;

        if (null == key) {
            LOG.error("key is null");
        } else {
            rtValue = getPropertiesValue(key);
        }

        if (null == rtValue) {
            LOG.warn("LoadProperties.getValues return null, key is: " + key);
            rtValue = defValue;
        }

        LOG.info("LoadProperties.getValues: key is: " + key + "; Value is: " + rtValue);

        return rtValue;
    }

    /**
     * 根据key值获取producer.properties的值
     *
     * @param key
     * @return
     */
    private String getPropertiesValue(String key) {
        String rtValue = producerProps.getProperty(key);

        return rtValue;
    }
}
